<template>
  <div>
    <home-head/>
    <div class="wrap">
      <!-- 轮播 -->
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="banner in banners" :key="banner.id">
          <img :src="banner.picUrl" alt="">
        </van-swipe-item>
      </van-swipe>
      <!-- /轮播 -->
      <!-- 宫格导航 -->
      <van-grid column-num="3" :clickable="true">
        <van-grid-item
          v-for="cate in cates"
          :key="cate.id"
          :icon="cate.icon"
          :to="'/itemLists/'+cate.id"
          :text="cate.name" />
      </van-grid>
      <!-- /宫格导航 -->
      <!-- 推荐商品 -->
      <items :items="items" @addCart="addCart" @clickItem="clickItem"/>
      <!-- /推荐商品 -->
    </div>
    <my-tabbar/>
  </div>
</template>

<script>
import MyTabbar from 'components/MyTabbar'
import HomeHead from './components/HomeHead.vue'
import Items from './components/Items'
import { fetchBanners, fetchCates, fetchItems } from 'api'
import cartMixin from 'mixins/addCart'

export default {
  name: 'home',
  mixins: [cartMixin],
  data () {
    return {
      banners: [],
      cates: [],
      recommendId: 72399,
      items: []
    }
  },
  created () {
    this.fetchBanners()
    this.fetchCates()
    this.fetchItems()
  },
  methods: {
    addCart (item) {
      this._addCart({ ...item, checked: true, num: 1 })
    },
    clickItem ({ id }) {
      // 点击商品
      this.$router.push({
        path: '/detail',
        query: {
          id
        }
      })
    },
    fetchBanners () { // 获取轮播数据
      fetchBanners().then(res => {
      // console.log(res)
        if (res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    },
    fetchCates () {
      // 获取所有分类
      fetchCates().then(res => {
      //  console.log(res)
        if (res.data.code === 0) {
          this.cates = res.data.data
        }
      })
    },
    fetchItems () {
      // 获取推荐商品
      fetchItems({ categoryId: this.recommendId }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          this.items = res.data.data
        }
      })
    }

  },
  components: {
    MyTabbar,
    HomeHead,
    Items
  }

}
</script>

<style lang="scss" scoped>
.wrap{
  margin:50px 0;
  .my-swipe{
    img{
      width:100%;
    }
  }
}
</style>
